package cn.airfei.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @description:
 * scattering:将数据写入到buffer时,可以采用buffer数组,依次写入 [分散]
 * gathering: 从buffer读取数据时,可以采用buffer数组依次读
 *
 * @author: air
 * @create: 2020-12-31 11:34
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        // 绑定端口
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffer=new ByteBuffer[2];
        byteBuffer[0]=ByteBuffer.allocate(5);
        byteBuffer[1]=ByteBuffer.allocate(3);

        // 等待客户端链接
        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true){
            int byteRead=0;
            while (byteRead<8){
                long read = socketChannel.read(byteBuffer);
                byteRead+=read;
                System.out.println("byteRead:"+byteRead);
                Arrays.stream(byteBuffer).map(buffer ->"position="+buffer.position()+",limit="+buffer.limit() ).forEach(System.out::println);
            }
            Arrays.stream(byteBuffer).forEach(buffer -> buffer.flip());
            // 将数据显示到客户端
            long byteWrite=0;
            while (byteWrite<8){
                long write = socketChannel.write(byteBuffer);
                byteWrite+=write;
            }
            // 将所有buffer进行clear
            Arrays.stream(byteBuffer).forEach(buffer -> buffer.clear());
            System.out.println("byteRead="+byteRead+",byteWrite="+byteWrite);
        }


    }
}
